<div class="config-container">
  <h3>Stages</h3>

  <% if (params[:stage_parent] == "pipelines") %>
      <%= form_for @pipeline, :as => :pipeline, :url => admin_stage_listing_path(), :html => {:method => :put, :id => 'pipeline_edit_form'} do |f| %>
          <%= md5_field %>

          <%= render :partial => "admin/shared/stage_configuration_type.html", :locals => {:scope => {:form => f, :pipeline => @pipeline}} -%>
          <div id="select_template_container" class="hidden">
            <% if @template_list.length > 0 %>
                <div class="fieldset">
                  <div class="form_item">
                    <div class="template_selection">
                      <%= f.label 'Template' %>
                      <% options_for_select_template = @template_list.map() {|template_view_model| template_view_model.getTemplate().name().to_s } %>
                      <%= f.select(com.thoughtworks.go.config.PipelineConfig::TEMPLATE_NAME, options_for_select_template, {:selected => @pipeline.getTemplateName()}, {:id => "select_template"}) %>
                      <span id="links" />
                    </div>

                  </div>
                </div>
              <% unless @is_config_repo_pipeline %>
                <div class="form_buttons">
                  <%= submit_button('SAVE', :class => 'primary skip_dirty_stop', :id => "submit_pipeline_edit_form", :onclick => "return false;") %>
                  <%= link_to 'RESET', admin_stage_listing_path(:current_tab => "stages"), :class => 'reset_button link_as_button', :id => 'reset_form' -%>
                </div>
              <% end %>
            <% else %>
                <div class="no_templates_message information">
                  There are no templates configured or you are unauthorized to view the existing templates.
                </div>
            <% end %>
          </div>

          <script type="text/javascript">
            $('submit_pipeline_edit_form').observe('click', function () {
              Modalbox.show(jQuery('#warning_prompt')[0], {
                overlayClose: false,
                title:        'Confirm Save'
              });
            });
          </script>
          <div id="warning_prompt" class="warning" style="display:none;">
            <div class="ui-dialog-content">
              <p>Switching to a template will cause all of the currently defined stages in this pipeline to be lost. Are you sure you want to continue?</p>
            </div>
            <div class="form_buttons actions">
              <%= submit_button('Proceed', :class => "primary", :onclick => "$('pipeline_edit_form').submit()") %>
              <%= submit_button('Cancel', :onclick => "Modalbox.hide()", :type => "button") %>
            </div>
          </div>

      <% end %>
  <% end %>

  <% if params[:stage_parent] == "templates" || @pipeline.getConfigurationType == com.thoughtworks.go.config.PipelineConfig::CONFIGURATION_TYPE_STAGES %>
      <div id="stages_list_container">
        <table class="list_table reorderable_table stages_listing">
          <thead>
          <tr>
          <% unless @is_config_repo_pipeline %>
            <th>Order</th>
          <% end %>
            <th>Stage</th>
            <th>Trigger Type</th>
            <th>Jobs</th>
          <% unless @is_config_repo_pipeline %>
            <th class="remove">Remove</th>
           <% end %>
          </tr>
          </thead>
          <tbody>
          <% @pipeline.each_with_index do |stage_config, stage_config_index| %>
              <tr class="stage_<%= stage_config.name() %>">
              <% unless @is_config_repo_pipeline %>
                <td>
                  <%= form_for stage_config, :as => :stage_config, :url => {:action => "decrement_index", :stage_name => stage_config.name(), :pipeline_name => @pipeline.name(), :type => params[:type]},
                               :html => {:method => :post} do |f| %>
                      <%= md5_field %>
                      <% unless stage_config_index == 0 %>
                          <button type="submit" value="" class="promote_button" title="Move Up">
                            <div class="promote_up"></div>
                          </button>
                      <% end %>
                  <% end %>
                  <%= form_for stage_config, :as => :stage_config, :url => {:action => "increment_index", :stage_name => stage_config.name(), :pipeline_name => @pipeline.name(), :type => params[:type]}, :html => {:method => :post} do |f| %>
                      <%= md5_field %>
                      <% unless stage_config_index == @pipeline.size()-1 %>
                          <button type="submit" value="" class="promote_button" title="Move Down">
                            <div class="promote_down"></div>
                          </button>
                      <% end %>
                  <% end %>
                </td>
              <% end %>
                <td class="stage_name"><%= link_to(stage_config.name(), admin_stage_edit_path(:stage_name => stage_config.name(), :current_tab => "settings"), :class => "stage_name_link") %></td>
                <td class="approval_type"><%= stage_config.getApproval().getDisplayName() %></td>
                <td class="number_of_jobs"><%= stage_config.allBuildPlans().size() %></td>
              <% unless @is_config_repo_pipeline %>
                <td class="remove">
                  <% if @stage_usage && @stage_usage.contains(stage_config) %>
                      <span class="icon_cannot_remove has_go_tip_right" title="Cannot delete this stage because it is used as a material in other pipelines"></span>
                  <% elsif @pipeline.size() == 1 %>

                      <%= action_icon({:type => "delete", :class => "has_go_tip_right", :title => "Cannot delete the only stage in a pipeline", :disabled => true}) %>
                      <!-- <span class="icon_cannot_remove has_go_tip_right" title=""></span> -->
                  <% else %>
                      <% unique_stage_delete_id = random_dom_id("delete_stage_") %>
                      <%= form_for stage_config, :as => :stage_config, :url => {:action => "destroy", :stage_name => stage_config.name()},
                                   :html => {:id => "#{unique_stage_delete_id}", :method => :delete} do |f| %>
                          <%= md5_field %>
                          <span class="icon_remove delete_parent" id="trigger_<%= unique_stage_delete_id %>">
                                    <%= render :partial => 'admin/shared/submit_with_prompt.html', :locals => {:scope => {:button_id => "trigger_#{unique_stage_delete_id}", :message => "Are you sure you want to delete the stage '#{stage_config.name()}' ? ", :on_confirmation_js => "$('#{"#{unique_stage_delete_id}"}').submit()"}} %>
                                </span>
                      <% end %>
                  <% end %>
                </td>
              <% end %>
              </tr>
          <% end %>
        <% unless @is_config_repo_pipeline %>
          <tr>
            <td>&nbsp;</td>
            <td colspan="4">
              <a class="add_link" href="#" onclick="ModalBoxWhichClosesAutoCompleteDropDownBeforeClosing.show('<%= admin_stage_new_path -%>', {overlayClose: false, title: 'Add Stage'})">Add new stage</a>
            </td>
          </tr>
        <% end %>
          </tbody>
        </table>
      </div>
  <% end %>
</div>
<script type="text/javascript">
  Util.on_load(function () {
    var hasSwitchedToTemplate = false;
    setConfigurationType      = function (element, isFirstTime) {
      var selected = jQuery(element).val();
      if (selected == "<%=com.thoughtworks.go.config.PipelineConfig::CONFIGURATION_TYPE_STAGES%>") {
        showElement(jQuery("#select_template_container"), false);
        showElement(jQuery("#stages_list_container"), true);
      } else if (selected == "<%=com.thoughtworks.go.config.PipelineConfig::CONFIGURATION_TYPE_TEMPLATE%>") {
        showElement(jQuery("#select_template_container"), true);
        showElement(jQuery("#stages_list_container"), false);
        if (!isFirstTime) {
          hasSwitchedToTemplate = true;
        }
      }
    };
    setConfigurationType(jQuery("input:[name='pipeline[configurationType]']:checked"), true);

    jQuery("input:[name='pipeline[configurationType]']").click(function () {
      setConfigurationType(this, false);
    });

    setViewAndEditLinks();
    jQuery("#select_template").change(function () {
      setViewAndEditLinks();
    });

    function setViewAndEditLinks() {
      var template_map = <%== @template_list.inject({})  {|memo, template_view_model | memo[template_view_model.getTemplate().name().to_s]  = {canView: template_view_model.isAuthorizedToViewTemplate(), canEdit: template_view_model.isAuthorizedToEditTemplate()}; memo}.to_json %>;
      viewAndEditAssociatedTemplate("#select_template").addViewAndEditTemplateLinks(template_map, "/go/admin/templates#!__template_name__/view", "<%= template_edit_path(:pipeline_name => "__template_name__" ,:stage_parent => "templates", :current_tab => 'general') %>");
    }
  });
  AjaxForm.error_box_selector = '#MB_content';
</script>
